import React, { RefObject, useEffect, useRef } from "react";
import { AssetCard } from "@/components";
import {
  Button,
  Collapse,
  DatePicker,
  Dialog,
  Input,
  Steps,
  Toast,
  Radio,
  Space,
} from "antd-mobile";
import type {
  WorkflowScheduleInfo,
  HomelistingsInfo,
  AddWorkflowScheduleReq,
  UpdateWorkflowScheduleReq,
} from "@/services";
import {
  addWorkflowSchedule,
  endWorkflow,
  getHomelistingInfoById,
  getSysRoleUnionMenuForRole,
  getWorkflowScheduleByWorkFlowId,
  updateWorkflowSchedule,
  WorkflowInfo,
} from "@/services";
import { useSafeState, useUpdate } from "ahooks";
import { trim } from "lodash-es";
import { EditSOutline, FlagOutline } from "antd-mobile-icons";
import dayjs from "dayjs";

interface ProcessItem {
  stepIndex: number;
  name: string;
  title: string;
  des: string;
  data: WorkflowScheduleInfo | undefined;
}

interface ProcessCardProps {
  record: WorkflowInfo;
  processOver: () => void;
}
const { Step } = Steps;

export const ProcessCard: React.FC<ProcessCardProps> = ({
  record,
  processOver,
}) => {
  const [datePickerVisible, setDatePickerVisible] = useSafeState(false);
  const [curProcessStep, setCurProcessStep] = useSafeState(-1);
  const processListRef = useRef<ProcessItem[]>([
    {
      stepIndex: 0,
      name: "A", //匹配数据的ID
      title: "签合同",
      des: "签署《帝房法拍服务合同》，业务部副总经理处领取合同并登记",
      data: undefined,
    },
    {
      stepIndex: 1,
      name: "B", //匹配数据的ID
      title: "归档",
      des: "签订合同后不超过 2 个工作日归档到业务部副总经理",
      data: undefined,
    },
    {
      stepIndex: 2,
      name: "C", //匹配数据的ID
      title: "建立 VIP 服务群",
      des: "业务部团队经理建立 VIP 服务群",
      data: undefined,
    },
    {
      stepIndex: 3,
      name: "D", //匹配数据的ID
      title: "按揭资料收集",
      des: "法拍顾问收集客户贷款资料（借款人夫妻双方身份证、户口本、婚姻证明、征信报告、收入证明）",
      data: undefined,
    },
    {
      stepIndex: 4,
      name: "E", //匹配数据的ID
      title: "尽职调查报告",
      des: "开拍前三天出尽调报告",
      data: undefined,
    },
    {
      stepIndex: 5,
      name: "F", //匹配数据的ID
      title: "参拍报名",
      des: "法拍顾问、业务部经理协助（7 大平台）",
      data: undefined,
    },
    {
      stepIndex: 6,
      name: "G", //匹配数据的ID
      title: "助拍",
      des: "开拍前一天填写好《助拍沟通表》详见附件一，与业务部团队经理沟通，提高客户预算，增加拍中率）",
      data: undefined,
    },
    {
      stepIndex: 7,
      name: "H", //匹配数据的ID
      title: "金融部通知客户带贷款资料",
      des: "金融部通知客户带好对应的贷款资料",
      data: undefined,
    },
    {
      stepIndex: 8,
      name: "I", //匹配数据的ID
      title: "参拍",
      des: "竞拍成功/未拍中",
      data: undefined,
    },
    {
      stepIndex: 9,
      name: "J", //匹配数据的ID
      title: "腾退/接房",
      des: "流程完成",
      data: undefined,
    },
  ]);
  const [actions, setActions] = useSafeState<string[]>([]);

  const getActionsRequest = async () => {
    const res = await getSysRoleUnionMenuForRole();
    if (res.code == 200) {
      const actions = res.data.list.filter((item) => item.type == 2);
      const acPerms = actions.map((item) => item.permissionCode);
      setActions(acPerms);
    }
  };

  const [assetDetail, setAssetDetail] = useSafeState<HomelistingsInfo>();
  const updateItemRef = useRef<ProcessItem>();
  const update = useUpdate();

  const getAssetsDetailRequest = async (onlyId: string) => {
    const res = await getHomelistingInfoById({
      onlyId,
    });
    if (res.code === 200) {
      setAssetDetail(res.data);
    } else {
      // handle error
      history.back();
    }
  };

  // 查询子流程
  const getChildProcessRequest = async (workflowId: string) => {
    const res = await getWorkflowScheduleByWorkFlowId({ workflowId });
    if (res.code == 200 && res.data.list.length > 0) {
      let newStepIndex = -1;
      processListRef.current = processListRef.current.map((item) => {
        const data = res.data.list.find((ite) => ite.name === item.name);
        if (data) {
          newStepIndex = item.stepIndex;
          item.data = data;
        }
        return item;
      });
      setCurProcessStep(newStepIndex);
      update();
    }
  };

  // 更新进度操作
  const updateWorkFlowStepHandle = async (
    values: Partial<AddWorkflowScheduleReq>
  ) => {
    const createMenuReq: AddWorkflowScheduleReq = {
      workflowId: record.onlyId, // 流程Id
      progressBusiness: "", // 业务进度
      personCharge: "", // 办理人
      handlingTime: "", // 办理时间
      name: "", // 进度名
    };
    const res = await addWorkflowSchedule(Object.assign(createMenuReq, values));
    if (res.code == 200) {
      Toast.show({
        icon: "success",
        content: "更新成功！",
      });
      getChildProcessRequest(record.onlyId);
    }
  };
  // 修改进度操作
  const editWorkFlowStepHandle = async (
    values: Partial<AddWorkflowScheduleReq>,
    childRecord: WorkflowScheduleInfo
  ) => {
    const updateReq: UpdateWorkflowScheduleReq = {
      onlyId: childRecord.onlyId,
      workflowId: record.onlyId,
      progressBusiness: "", // 业务进度
      personCharge: "", // 办理人
      handlingTime: "", // 办理时间
      name: "", // 进度名
      ...values,
    };
    const res = await updateWorkflowSchedule(updateReq);
    if (res.code == 200) {
      Toast.show({
        icon: "success",
        content: "更新成功！",
      });
      getChildProcessRequest(record.onlyId);
    }
  };

  const endWorkflowHandle = async () => {
    const confirm = await Dialog.confirm({
      title: "提示",
      content: "确定结束流程吗？",
    });
    if (confirm) {
      const res = await endWorkflow({
        onlyId: record.onlyId,
        workFlowResults: 1, // 0-未处理；1-未拍中；2-已拍中
      });
      if (res.code == 200) {
        Toast.show({
          icon: "success",
          content: "更新成功！",
        });
        processOver();
      }
    }
  };

  const checkAction = (processItem: ProcessItem) => {
    // actions?.includes('operation:assign')
    if (processItem.stepIndex == 1) {
      return !actions?.includes("process:operation:archiving");
    }
    if (processItem.stepIndex == 3) {
      return !actions?.includes("process:operation:collection");
    }
    if (processItem.stepIndex == 4) {
      return !actions?.includes("process:operation:report");
    }
  };

  useEffect(() => {
    getActionsRequest();
    getAssetsDetailRequest(record.homeId);
  }, [record]);

  return (
    <div
      className={
        (record.isEnd == 1 ? "text-gray-4" : " ") + " w-full mb-10px bg-white"
      }
    >
      {/* header */}
      <div className="flex justify-between px-2 pt-10px items-center">
        <div className="font-bold truncate">{record.title}</div>
        <div className="w-170px ml-10px text-right">
          {record.createTime.split("+0800")[0].trim()}
        </div>
      </div>
      <div className="h-1px w-full bg-gray-1 mt-10px"></div>

      {assetDetail && <AssetCard record={assetDetail} />}
      <div>
        <Collapse
          accordion
          onChange={(activeKey: string | null) => {
            if (activeKey == "process") {
              getChildProcessRequest(record.onlyId);
            }
          }}
        >
          <Collapse.Panel key="user" title="客户信息">
            <div className="text-16px">
              <div className="flex justify-between ">
                <div className="text-gray-5">用户姓名：</div>
                <div>
                  {record.nickName}({record.realName})
                </div>
              </div>
              <div className="flex justify-between  mt-10px">
                <div className="text-gray-5">联系手机：</div>
                <div>{record.tel}</div>
              </div>
            </div>
          </Collapse.Panel>
          {/* record.isEnd == 1 */}
          <Collapse.Panel
            key="process"
            title={
              <>
                <span>服务进度</span>
                <span className="text-13px ml-6px">
                  {record.isEnd == 1 && (
                    <span className="text-red-6 mr-6px">流程已完结</span>
                  )}
                  {record.workFlowResults == 1 && (
                    <span className="text-red-6">(未拍中)</span>
                  )}
                  {record.workFlowResults == 2 && (
                    <span className="text-blue-6">(已拍中)</span>
                  )}
                </span>
              </>
            }
          >
            <Steps
              direction="vertical"
              current={curProcessStep}
              style={{
                "--title-font-size": "16px",
                "--description-font-size": "15px",
                "--indicator-margin-right": "6px",
              }}
            >
              {processListRef.current.map((item, index) => (
                <Step
                  key={index}
                  title={
                    <>
                      <span
                        className={
                          "font-bold " +
                          (curProcessStep == index ? "text-blue-6" : "")
                        }
                      >
                        {item.title}
                      </span>
                    </>
                  }
                  description={
                    <>
                      <div>
                        {item.stepIndex != 8 && <span>{item.des}</span>}
                        {item.stepIndex == 8 && (
                          // 0-未处理；1-未拍中；2-已拍中
                          <span>
                            {record.workFlowResults == 0 ? (
                              item.des
                            ) : record.workFlowResults == 1 ? (
                              <span>
                                <span className="text-red-6">未拍中</span>
                                <span className="text-red-6 ml-5px">
                                  {record.resultsUpdateTime}
                                </span>
                              </span>
                            ) : (
                              <span>
                                <span className="text-blue-6 font-bold">
                                  已拍中
                                </span>
                                <span className="text-blue-6 ml-5px">
                                  {record.resultsUpdateTime}
                                </span>
                              </span>
                            )}
                          </span>
                        )}
                      </div>
                      {item.data && (
                        <div className="text-blue-6">
                          <span>{item.data.personCharge}</span>
                          <span className="ml-6px">
                            {item.data?.handlingTime}
                          </span>
                        </div>
                      )}
                      {record.isEnd == 0 && index <= curProcessStep + 1 && (
                        <div className="mt-10px flex items-center">
                          <Button
                            color="primary"
                            fill="outline"
                            disabled={checkAction(item)}
                            onClick={() => {
                              updateItemRef.current = item;
                              setDatePickerVisible(true);
                            }}
                          >
                            <div className="flex items-center">
                              {item.stepIndex - 1 == curProcessStep ? (
                                <FlagOutline />
                              ) : (
                                <EditSOutline />
                              )}
                              <span className="ml-4px">
                                {item.stepIndex - 1 == curProcessStep
                                  ? "更新进度"
                                  : "修改"}
                              </span>
                            </div>
                          </Button>
                          {/* {item.stepIndex == 8 && (
                            <Button
                              color="danger"
                              fill="outline"
                              disabled={curProcessStep < item.stepIndex}
                              className="ml-6px"
                              onClick={() => endWorkflowHandle()}
                            >
                              结束流程(未拍中)
                            </Button>
                          )} */}
                        </div>
                      )}
                    </>
                  }
                />
              ))}
            </Steps>
          </Collapse.Panel>
        </Collapse>
      </div>
      <DatePicker
        precision="minute"
        defaultValue={
          updateItemRef.current?.data?.handlingTime
            ? new Date(updateItemRef.current?.data!.handlingTime)
            : dayjs().toDate()
        }
        max={new Date()}
        visible={datePickerVisible}
        onClose={() => setDatePickerVisible(false)}
        onConfirm={async (value) => {
          let realName = updateItemRef.current?.data?.personCharge || "";
          let result = "";
          const confirm = await Dialog.confirm({
            title: "更新进度",
            content: (
              <>
                <div className="border-1px border-gray-1  border-solid h-40px flex items-center px-10px rounded">
                  <Input
                    type="text"
                    defaultValue={realName}
                    placeholder="请输入处理人姓名"
                    onChange={(val) => {
                      realName = trim(val);
                    }}
                  />
                </div>
              </>
            ),
          });
          if (confirm) {
            if (updateItemRef.current?.stepIndex == 8) {
              // 选择拍卖结果
              const resultConfirm = await Dialog.confirm({
                title: "拍卖结果",
                content: (
                  <>
                    <div className="border-1px border-gray-1  border-solid h-40px flex items-center px-10px rounded">
                      <Radio.Group
                        defaultValue="success"
                        onChange={(val) => {
                          result = val.toString();
                        }}
                      >
                        <Space direction="horizontal">
                          <Radio value="success" className="text-green-6">
                            参拍成功
                          </Radio>
                          <Radio value="fail" className="text-red-6">
                            未拍中
                          </Radio>
                        </Space>
                      </Radio.Group>
                    </div>
                  </>
                ),
              });
              if (resultConfirm) {
                // result
                if (result == "success") {
                  // 参拍成功
                  const res = await endWorkflow({
                    onlyId: record.onlyId,
                    workFlowResults: 2, // 0-未处理；1-未拍中；2-已拍中
                  });
                  if (res.code != 200) {
                    return;
                  }
                } else {
                  //  未拍中
                  const res = await endWorkflow({
                    onlyId: record.onlyId,
                    workFlowResults: 1, // 0-未处理；1-未拍中；2-已拍中
                  });
                  if (res.code != 200) {
                    return;
                  }
                }
                processOver();
              } else {
                return;
              }
            }
            if (updateItemRef.current?.data) {
              editWorkFlowStepHandle(
                {
                  progressBusiness: updateItemRef.current?.title, // 业务进度
                  personCharge: realName, // 办理人
                  handlingTime: dayjs(value).format("YYYY-MM-DD HH:mm:ss"), // 办理时间
                  name: updateItemRef.current?.name, // 进度名
                },
                updateItemRef.current?.data
              );
            } else {
              updateWorkFlowStepHandle({
                progressBusiness: updateItemRef.current?.title, // 业务进度
                personCharge: realName, // 办理人
                handlingTime: dayjs(value).format("YYYY-MM-DD HH:mm:ss"), // 办理时间
                name: updateItemRef.current?.name, // 进度名
              });
            }
          }
        }}
      ></DatePicker>
    </div>
  );
};
